package com.ssm.service;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.ssm.dao.IArticleDao;
import com.ssm.entity.Article;
import com.ssm.entity.ArticleCategory;
import com.ssm.entity.ArticleTag;

@Service
public class ArticleServiceImpl {
    @Autowired
    private IArticleDao articleDao;
    
    // 查询所有分类
    public String findAllCategories() {
        List<ArticleCategory> categories = articleDao.findAllCategories();
        JSONObject obj = new JSONObject();
        JSONArray data = new JSONArray();
        
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        
        for (ArticleCategory category : categories) {
            JSONArray arr = new JSONArray();
            arr.add(category.getCid());
            arr.add(category.getCname());
            
            String parentName = "无父级";
            if (category.getParent() != null) {
                parentName = category.getParent().getCname();
            }
            arr.add(parentName);
            
            arr.add(category.getDescription());
            String createTime = category.getCreate_time() != null ? 
                    sdf.format(category.getCreate_time()) : sdf.format(new Date());
            arr.add(createTime);
            
            data.add(arr);
        }
        
        obj.put("data", data);
        return obj.toJSONString();
    }
    
    // 查询所有标签
    public String findAllTags() {
        List<ArticleTag> tags = articleDao.findAllTags();
        JSONObject obj = new JSONObject();
        JSONArray data = new JSONArray();
        
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        
        for (ArticleTag tag : tags) {
            JSONArray arr = new JSONArray();
            arr.add(tag.getTid());
            arr.add(tag.getTname());
            arr.add(tag.getDescription());
            String createTime = tag.getCreate_time() != null ? 
                    sdf.format(tag.getCreate_time()) : sdf.format(new Date());
            arr.add(createTime);
            
            data.add(arr);
        }
        
        obj.put("data", data);
        return obj.toJSONString();
    }
    
    // 查询所有文章
    public String findAll() {
        List<Map<String, Object>> articles = articleDao.findAll();
        JSONObject obj = new JSONObject();
        JSONArray data = new JSONArray();
        
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        
        for (Map<String, Object> article : articles) {
            JSONArray arr = new JSONArray();
            arr.add(article.get("aid"));
            arr.add(article.get("title"));
            arr.add(article.get("cname"));
            arr.add(article.get("uname"));
            
            String createTime = "";
            if (article.get("create_time") != null) {
                if (article.get("create_time") instanceof Date) {
                    createTime = sdf.format(article.get("create_time"));
                } else {
                    createTime = article.get("create_time").toString();
                }
            }
            arr.add(createTime);
            
            arr.add(article.get("view_count"));
            arr.add(article.get("status"));
            
            data.add(arr);
        }
        
        obj.put("data", data);
        return obj.toJSONString();
    }
    
    // 根据用户ID查询文章
    public String findByUser(int uid) {
        List<Map<String, Object>> articles = articleDao.findByUser(uid);
        JSONObject obj = new JSONObject();
        JSONArray data = new JSONArray();
        
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        
        for (Map<String, Object> article : articles) {
            JSONArray arr = new JSONArray();
            arr.add(article.get("aid"));
            arr.add(article.get("title"));
            arr.add(article.get("cname"));
            
            String createTime = "";
            if (article.get("create_time") != null) {
                if (article.get("create_time") instanceof Date) {
                    createTime = sdf.format(article.get("create_time"));
                } else {
                    createTime = article.get("create_time").toString();
                }
            }
            arr.add(createTime);
            
            arr.add(article.get("view_count"));
            arr.add(article.get("status"));
            
            data.add(arr);
        }
        
        obj.put("data", data);
        return obj.toJSONString();
    }
    
    // 获取分类详情
    public String getCategory(int cid) {
        ArticleCategory category = articleDao.getCategoryById(cid);
        if (category == null) {
            return "{}";
        }
        
        JSONObject obj = new JSONObject();
        obj.put("cid", category.getCid());
        obj.put("cname", category.getCname());
        obj.put("description", category.getDescription());
        obj.put("parent_id", category.getParent_id());
        
        return obj.toJSONString();
    }
    
    // 获取标签详情
    public String getTag(int tid) {
        ArticleTag tag = articleDao.getTagById(tid);
        if (tag == null) {
            return "{}";
        }
        
        JSONObject obj = new JSONObject();
        obj.put("tid", tag.getTid());
        obj.put("tname", tag.getTname());
        obj.put("description", tag.getDescription());
        
        return obj.toJSONString();
    }
    
    // 获取文章详情
    public String get(int aid) {
        Article article = articleDao.getById(aid);
        if (article == null) {
            return "{}";
        }
        
        JSONObject obj = new JSONObject();
        obj.put("aid", article.getAid());
        obj.put("title", article.getTitle());
        obj.put("content", article.getContent());
        obj.put("summary", article.getSummary());
        obj.put("cid", article.getCid());
        obj.put("uid", article.getUid());
        obj.put("view_count", article.getView_count());
        obj.put("status", article.getStatus());
        
        return obj.toJSONString();
    }
    
    // 查询父级分类（用于下拉框）
    public String findParentCategories() {
        List<ArticleCategory> categories = articleDao.findParentCategories();
        JSONObject obj = new JSONObject();
        JSONArray data = new JSONArray();
        
        for (ArticleCategory category : categories) {
            JSONArray arr = new JSONArray();
            arr.add(category.getCid());
            arr.add(category.getCname());
            data.add(arr);
        }
        
        obj.put("data", data);
        return obj.toJSONString();
    }
    
    // 添加分类
    public String addCategory(String cname, String description, int parent_id) {
        if (cname == null || cname.trim().isEmpty()) {
            return "{\"Status\":\"error\",\"msg\":\"分类名称不能为空\"}";
        }
        
        ArticleCategory category = new ArticleCategory();
        category.setCname(cname);
        category.setDescription(description);
        category.setParent_id(parent_id);
        
        int count = articleDao.addCategory(category);
        String status = count > 0 ? "ok" : "error";
        String msg = count > 0 ? "分类添加成功" : "分类添加失败";
        
        JSONObject obj = new JSONObject();
        obj.put("Status", status);
        obj.put("msg", msg);
        return obj.toJSONString();
    }
    
    // 更新分类
    public String updateCategory(int cid, String cname, String description, int parent_id) {
        if (cname == null || cname.trim().isEmpty()) {
            return "{\"Status\":\"error\",\"msg\":\"分类名称不能为空\"}";
        }
        
        if (cid == parent_id) {
            return "{\"Status\":\"error\",\"msg\":\"父级分类不能选择自己\"}";
        }
        
        ArticleCategory category = new ArticleCategory();
        category.setCid(cid);
        category.setCname(cname);
        category.setDescription(description);
        category.setParent_id(parent_id);
        
        int count = articleDao.updateCategory(category);
        String status = count > 0 ? "ok" : "error";
        String msg = count > 0 ? "分类更新成功" : "分类更新失败";
        
        JSONObject obj = new JSONObject();
        obj.put("Status", status);
        obj.put("msg", msg);
        return obj.toJSONString();
    }
    
    // 删除分类
    public String deleteCategory(int cid) {
        // 检查分类下是否有子分类或文章，如果有，则不允许删除
        int childCount = articleDao.countChildCategories(cid);
        if (childCount > 0) {
            return "{\"Status\":\"error\",\"msg\":\"该分类下有子分类，不能删除\"}";
        }
        
        int articleCount = articleDao.countArticleByCategory(cid);
        if (articleCount > 0) {
            return "{\"Status\":\"error\",\"msg\":\"该分类下有文章，不能删除\"}";
        }
        
        int count = articleDao.deleteCategory(cid);
        String status = count > 0 ? "ok" : "error";
        String msg = count > 0 ? "分类删除成功" : "分类删除失败";
        
        JSONObject obj = new JSONObject();
        obj.put("Status", status);
        obj.put("msg", msg);
        return obj.toJSONString();
    }
    
    // 添加标签
    public String addTag(String tname, String description) {
        if (tname == null || tname.trim().isEmpty()) {
            return "{\"Status\":\"error\",\"msg\":\"标签名称不能为空\"}";
        }
        
        ArticleTag tag = new ArticleTag();
        tag.setTname(tname);
        tag.setDescription(description);
        
        int count = articleDao.addTag(tag);
        String status = count > 0 ? "ok" : "error";
        String msg = count > 0 ? "标签添加成功" : "标签添加失败";
        
        JSONObject obj = new JSONObject();
        obj.put("Status", status);
        obj.put("msg", msg);
        return obj.toJSONString();
    }
    
    // 更新标签
    public String updateTag(int tid, String tname, String description) {
        if (tname == null || tname.trim().isEmpty()) {
            return "{\"Status\":\"error\",\"msg\":\"标签名称不能为空\"}";
        }
        
        ArticleTag tag = new ArticleTag();
        tag.setTid(tid);
        tag.setTname(tname);
        tag.setDescription(description);
        
        int count = articleDao.updateTag(tag);
        String status = count > 0 ? "ok" : "error";
        String msg = count > 0 ? "标签更新成功" : "标签更新失败";
        
        JSONObject obj = new JSONObject();
        obj.put("Status", status);
        obj.put("msg", msg);
        return obj.toJSONString();
    }
    
    // 删除标签
    public String deleteTag(int tid) {
        // 检查标签是否被文章使用，如果有，则不允许删除
        int usageCount = articleDao.countTagUsage(tid);
        if (usageCount > 0) {
            return "{\"Status\":\"error\",\"msg\":\"该标签已被文章使用，不能删除\"}";
        }
        
        int count = articleDao.deleteTag(tid);
        String status = count > 0 ? "ok" : "error";
        String msg = count > 0 ? "标签删除成功" : "标签删除失败";
        
        JSONObject obj = new JSONObject();
        obj.put("Status", status);
        obj.put("msg", msg);
        return obj.toJSONString();
    }
    
    // 添加文章
    public String add(String title, String content, String summary, int cid, int uid) {
        if (title == null || title.trim().isEmpty()) {
            return "{\"Status\":\"error\",\"msg\":\"文章标题不能为空\"}";
        }
        
        if (content == null || content.trim().isEmpty()) {
            return "{\"Status\":\"error\",\"msg\":\"文章内容不能为空\"}";
        }
        
        Article article = new Article();
        article.setTitle(title);
        article.setContent(content);
        article.setSummary(summary);
        article.setCid(cid);
        article.setUid(uid);
        article.setStatus(1); // 默认为已发布状态
        
        int count = articleDao.add(article);
        String status = count > 0 ? "ok" : "error";
        String msg = count > 0 ? "文章添加成功" : "文章添加失败";
        
        JSONObject obj = new JSONObject();
        obj.put("Status", status);
        obj.put("msg", msg);
        return obj.toJSONString();
    }
    
    // 更新文章
    public String update(int aid, String title, String content, String summary, int cid, int uid) {
        if (title == null || title.trim().isEmpty()) {
            return "{\"Status\":\"error\",\"msg\":\"文章标题不能为空\"}";
        }
        
        if (content == null || content.trim().isEmpty()) {
            return "{\"Status\":\"error\",\"msg\":\"文章内容不能为空\"}";
        }
        
        Article article = new Article();
        article.setAid(aid);
        article.setTitle(title);
        article.setContent(content);
        article.setSummary(summary);
        article.setCid(cid);
        article.setUid(uid);
        article.setStatus(1); // 默认为已发布状态
        
        int count = articleDao.update(article);
        String status = count > 0 ? "ok" : "error";
        String msg = count > 0 ? "文章更新成功" : "文章更新失败";
        
        JSONObject obj = new JSONObject();
        obj.put("Status", status);
        obj.put("msg", msg);
        return obj.toJSONString();
    }
    
    // 删除文章
    public String delete(int aid, int uid) {
        int count = articleDao.delete(aid);
        String status = count > 0 ? "ok" : "error";
        String msg = count > 0 ? "文章删除成功" : "文章删除失败";
        
        JSONObject obj = new JSONObject();
        obj.put("Status", status);
        obj.put("msg", msg);
        return obj.toJSONString();
    }
    
    // 为文章添加标签
    public String addTagToArticle(int aid, int tid) {
        int count = articleDao.addArticleTag(aid, tid);
        String status = count > 0 ? "ok" : "error";
        String msg = count > 0 ? "标签添加成功" : "标签添加失败";
        
        JSONObject obj = new JSONObject();
        obj.put("Status", status);
        obj.put("msg", msg);
        return obj.toJSONString();
    }
    
    // 从文章中删除标签
    public String removeTagFromArticle(int aid, int tid) {
        int count = articleDao.deleteArticleTag(aid, tid);
        String status = count > 0 ? "ok" : "error";
        String msg = count > 0 ? "标签移除成功" : "标签移除失败";
        
        JSONObject obj = new JSONObject();
        obj.put("Status", status);
        obj.put("msg", msg);
        return obj.toJSONString();
    }
    
    // 获取文章的标签
    public String getArticleTags(int aid) {
        List<ArticleTag> tags = articleDao.getArticleTags(aid);
        JSONObject obj = new JSONObject();
        JSONArray data = new JSONArray();
        
        for (ArticleTag tag : tags) {
            JSONArray arr = new JSONArray();
            arr.add(tag.getTid());
            arr.add(tag.getTname());
            data.add(arr);
        }
        
        obj.put("data", data);
        return obj.toJSONString();
    }
} 